package com.pai4j.zwiki.repository;

import com.pai4j.zwiki.domain.entity.ThesisVersionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 论文版本数据访问层
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Repository
public interface ThesisVersionRepository extends JpaRepository<ThesisVersionEntity, Long> {

    /**
     * 通过任务ID查找所有版本
     */
    List<ThesisVersionEntity> findByTaskIdOrderByVersionDesc(String taskId);

    /**
     * 通过任务ID和版本号查找
     */
    Optional<ThesisVersionEntity> findByTaskIdAndVersion(String taskId, Integer version);

    /**
     * 查找当前版本
     */
    Optional<ThesisVersionEntity> findByTaskIdAndIsCurrentTrue(String taskId);

    /**
     * 获取最新版本号
     */
    default Integer getLatestVersion(String taskId) {
        return findByTaskIdOrderByVersionDesc(taskId)
                .stream()
                .findFirst()
                .map(ThesisVersionEntity::getVersion)
                .orElse(0);
    }
}

